package cz.data.common.mongo.utils;

import cz.data.common.support.db.manage.Condition;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.mongodb.core.query.Criteria;

import java.util.Objects;

public class CriteriaUtils {

    public static void builder(Criteria criteria, Condition condition) {
        switch (condition.getQueryType()) {
            case "eq":
                if (isNotBlank(condition.getValue())) {
                    criteria.and(condition.getColumn()).is(condition.getValue());
                }
                break;
            case "ne":
                if (isNotBlank(condition.getValue())) {
                    criteria.and(condition.getColumn()).ne(condition.getValue());
                }
                break;
            case "like":
                if (isNotBlank(condition.getValue())) {
                    criteria.and(condition.getColumn()).regex(String.valueOf(condition.getValue()));
                }
                break;
            case "gt":
                if (isNotBlank(condition.getValue())) {
                    criteria.and(condition.getColumn()).gt(condition.getValue());
                }
                break;
            case "ge":
                if (isNotBlank(condition.getValue())) {
                    criteria.and(condition.getColumn()).gte(condition.getValue());
                }
                break;
            case "lt":
                if (isNotBlank(condition.getValue())) {
                    criteria.and(condition.getColumn()).lt(condition.getValue());
                }
                break;
            case "le":
                if (isNotBlank(condition.getValue())) {
                    criteria.and(condition.getColumn()).lte(condition.getValue());
                }
                break;
            case "between":
                if (isNotBlank(condition.getLeftValue()) && isNotBlank(condition.getRightValue())) {
                    criteria.and(condition.getColumn())
                            .gt(condition.getLeftValue())
                            .lt(condition.getRightValue());
                }
                break;
            default:
                break;
        }
    }

    public static boolean isNotBlank(Object value) {
        return Objects.nonNull(value) && StringUtils.isNotBlank(value.toString());
    }
}
